#include <func.h>

#define MAX_USER 10
#define MAXSIZE_MESSAGE 512

int main(int argc,char **argv)
{
    ARGS_CHECK(argc,3);
    int socketFd;
    socketFd = socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(socketFd,-1,"socket");
    printf("get socketFd:%d\n",socketFd);
    struct sockaddr_in ser;
    memset(&ser,0,sizeof(ser));
    ser.sin_family=AF_INET;
    ser.sin_port=htons(atoi(argv[2]));
    ser.sin_addr.s_addr=inet_addr(argv[1]);
    
    int ret;
    ret = bind(socketFd,(struct sockaddr *)&ser,sizeof(ser));
    ERROR_CHECK(ret,-1,"bind");
label:
    printf("server listening...\n");
    listen(socketFd,MAX_USER);
    
    int newLinkFd;
    struct sockaddr_in client;
    memset(&client,0,sizeof(client));
    socklen_t len = sizeof(client);
    newLinkFd = accept(socketFd,(struct sockaddr *)&client,&len);
    ERROR_CHECK(newLinkFd,-1,"accept");
    printf("newlinkfd: %d\n",newLinkFd);
    //新用户接入信息，可以用于扩展打印用户名
    printf("accept a new user! client ip = %s, client port = %d\n",\
           inet_ntoa(client.sin_addr),ntohs(client.sin_port));
    
    char buf[MAXSIZE_MESSAGE] = {0};
    fd_set rdset;
    while(1)
    {
        FD_ZERO(&rdset);
        FD_SET(STDIN_FILENO,&rdset);
        FD_SET(newLinkFd,&rdset);

        if(select(newLinkFd+1,&rdset,NULL,NULL,NULL))
        {
            if(FD_ISSET(newLinkFd,&rdset))//检测到用户的消息
            {
                memset(buf,0,sizeof(buf));
                ret = recv(newLinkFd,buf,sizeof(buf),0);
                if(!ret)
                {
                    printf("client disconnected\n");
                    goto label;
                }
                printf("recv:%s\n",buf);
            }
            if(FD_ISSET(STDIN_FILENO,&rdset))
            {
                memset(buf,0,sizeof(buf));
                read(STDIN_FILENO,buf,sizeof(buf));
                send(newLinkFd,buf,strlen(buf) -1,0);
            }
        }
    }

    close(newLinkFd);
    close(socketFd);
    return 0;
}

